package chances.epg.session;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

import org.slf4j.Logger;
import org.springframework.util.StringUtils;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.SpringWebUtils;

public class UserSessionHelper {

	private static final Logger logger = EpgLogFactory.getSystemLogger();
	public static final String USER_SESSION_NAME = "EPG_USER_SESSION";
	public static final String USER_ID_COOKIES_NAME = "cs_stb_no";
	public static final String USER_ID_NAME = "userId";

	public static UserSessionService getUserSessionService(HttpServletRequest request) {

		UserSessionService userSessionService = SpringWebUtils.findBean(request, UserSessionService.class);
		return userSessionService;
	}

	/**
	 * 获取UserSession.
	 * 
	 * @param request
	 * @return
	 */
	public static final UserSession getUserSession(HttpServletRequest request) {
		return getUserSessionFromSession(request);
//
//		String userId = getUserId(request);
//		if (StringUtils.isEmpty(userId)) {
//		} else {
//			return getUserSessionService(request).get(userId);
//		}
	}

	/**
	 * 获取UserSession.
	 * 
	 * @param context
	 * @return
	 */
	public static final UserSession getUserSession(PageContext context) {
		return getUserSession((HttpServletRequest) context.getRequest());
	}

	public static final UserSession getUserSessionFromSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return (UserSession) session.getAttribute(USER_SESSION_NAME);
	}

	/**
	 * 保存UserSession.
	 * 
	 * @param request
	 * @param userSession
	 */
	public static final void saveUserSessionToSession(HttpServletRequest request, UserSession userSession) {
		HttpSession session = request.getSession();
		session.setAttribute(USER_SESSION_NAME, userSession);
		logger.debug("save user session.sessionId={}", session.getId());
	}

	/**
	 * 清除UserSession.
	 * 
	 * @param request
	 */
	public static final void removeUserSessionFromSession(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			session = request.getSession();
		}

		if (session != null) {
			session.removeAttribute(USER_SESSION_NAME);
			logger.debug("remove user session.sessionId={}", session.getId());
		}
	}

	/**
	 * 
	 * @param request
	 */
	public static String getUserIdFromCookies(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookie.getName().equals(USER_ID_COOKIES_NAME)) {
				return cookie.getValue();
			}
		}
		return null;
	}

	/**
	 * 
	 * @param request
	 */
	public static void saveUserIdToCookies(HttpServletResponse response, String id) {
		Cookie cookies = new Cookie(USER_ID_COOKIES_NAME, id);
		cookies.setPath("/");
		response.addCookie(cookies);
	}

	/**
	 * 
	 * @param request
	 */
	public static void removeUserIdToCookies(HttpServletResponse response) {
		Cookie cookie = new Cookie(USER_ID_COOKIES_NAME, null);
		cookie.setPath("/");
		cookie.setHttpOnly(true);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	/**
	 * 
	 * @param request
	 */
	public static String getUserId(HttpServletRequest request) {
		String userId = request.getParameter(USER_ID_NAME);
		if (StringUtils.isEmpty(userId)) {
			userId = getUserIdFromCookies(request);
		}
		return userId;
	}

	public static UserSession getUserSessionFromCookie(HttpServletRequest request) {
		UserSessionService userSessionService = SpringWebUtils.findBean(request, UserSessionService.class);
		String userId = getUserIdFromCookies(request);
		if(userId != null){
			UserSession result = userSessionService.get(userId);
			logger.info("load user Session from cooke {}={}" ,userId ,result);
			return result;
		}
		return null;
	}

	/*public static void saveWechatToken(HttpServletRequest request, WechatToken token) {
		UserSession userSession = getUserSessionFromSession(request);
		userSession.setUserId(token.getOpenId());
		userSession.setUsertoken(token.getToken());
		saveUserSessionToSession(request, userSession);
	}*/
	
}
